import Footer from '@/components/Footer';

import { AvatarDropdown, AvatarName } from '@/components/AvatarDropdown';
import Copilot from '@/components/Copilot';
import { Question } from '@/components/Question';
import { CurrentUser } from '@/data/login';
import { getIcon } from '@/enums/icon';
import { list, query } from '@/services/data';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { Drawer } from 'antd';
import { useState } from 'react';
import defaultSettings from '../config/defaultSettings';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<CurrentUser>;
}> {
  const fetchUserInfo = async () => {
    try {
      const { data }: any = await query('/system/index/current');
      return data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const { location } = history;
  if (
    ![
      '/turing/user/login',
      '/turing/user/password/forgot',
      '/turing/user/register',
      '/turing/user/register-result',
    ].includes(location.pathname)
  ) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

const processRoutes = (routes: any, parentPath = '') => {
  return routes.map(({ path: subPath, name, routes: childRoutes }: any) => {
    const fullPath = parentPath ? `${parentPath}/${subPath}` : subPath;

    const route: any = {
      path: fullPath,
      name,
    };

    // 如果存在子路由，递归处理
    if (childRoutes && childRoutes.length > 0) {
      route.routes = processRoutes(childRoutes, fullPath);
    }

    return route;
  });
};

export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const [copilotOpen, setCopilotOpen] = useState(true);

  return {
    menu: {
      params: {
        userId: initialState?.currentUser?.id,
      },
      request: async () => {
        const menuData: any = await list('/system/index/current/routes');
        const routes: any = (menuData?.list || []).map(({ icon, routes: rs, path, name }: any) => {
          const route: any = {
            name,
            path,
            icon: getIcon(icon),
          };

          // 递归处理子路由
          if (rs && rs.length > 0) {
            route.routes = processRoutes(rs, path);
          }

          return route;
        });

        return routes;
      },
    },

    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    actionsRender: () => [<Question key="doc" />],

    waterMarkProps: {
      content: initialState?.currentUser?.username,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: isDev ? [] : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          <Drawer
            placement={'right'}
            closable={false}
            onClose={() => setCopilotOpen(false)}
            open={copilotOpen}
            key={'placement'}
            mask={false}
            width={420}
          >
            <Copilot copilotOpen={copilotOpen} setCopilotOpen={setCopilotOpen} />
          </Drawer>

          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
